pacman::p_load(readxl, gifski, gapminder,
plotly, gganimate, tidyverse)Hands-On Exercise 3-2: Programming Animated Statistical Graphics with R
3-2: 1 Overview
When telling a visually-driven data story, animated graphics tends to attract the interest of the audience and make deeper impression than static graphics. In this hands-on exercise, animated data visualisation will be created using gganimate and plotly r packages. At the same time, data (i) reshaped by using tidyr package, and (ii) processed, wrangled and transformed with dplyr package.
3-2: 1.1 Basic Xoncepts of Animation
When creating animations, the plot does not actually move. Instead, many individual plots are built and then stitched together as movie frames, just like an old-school flip book or cartoon. Each frame is a different plot to convey motion, which is built using some relevant subset of the aggregated data.The subset drives the flow of the animation when stitched back together.

3-2: 1.2 Terminology
Before diving into the steps for creating an animated statistical graph, it is important to understand some of the key concepts and terminology related to this type of visualisation.
- Frame: In an animated line graph, each frame represents a different point in time or a different category. When the frame changes, the data points on the graph are updated to reflect the new data.
- Animation Attributes: The animation attributes are the settings that control how the animation behaves. For example, you can specify the duration of each frame, the easing function used to transition between frames, and whether to start the animation from the current frame or from the beginning.
Before making animated graphs, think of the above question first.
- An animated graphic may not be worth the time investment for just exploratory data analysis.
- However, in a presentation, a few well-placed animated graphics can help an audience connect with your topic remarkably better than static counterparts.
3-2: 2 Getting Started
3-2: 2.1 Loading the R packages
First, write a code chunk to check, install and load the following R packages:
- plotly: An R library for plotting interactive statistical graphs
- gganimate: A ggplot extension for creating animated statistical graphs
- gifski: Converts video frames to GIF animations using pngquant’s fancy features for efficient cross-frame palettes and temporal dithering. It produces animated GIFs that use thousands of colours per frame.
- gapminer: An excerpt of the data available at Gapminder.org. We just want to use its country_colors scheme
- tidyverse: A family of modern R packages specially designed to support data science, analysis and communication task including creating static statistical graphs.
3-2: 2.2 Importing the Data
In this hands-on exercise, the Data worksheet from GlobalPopulation Excel workbook will be used.
Write a code chunk to import Data worksheet from GlobalPopulation Excel workbook by using appropriate R package from tidyverse family.
col <- c("Country", "Continent")
globalPop <- read_xls("data/GlobalPopulation.xls",
sheet="Data") %>%
mutate_each_(funs(factor(.)), col) %>% # mutate_each
mutate(Year = as.integer(Year))read_xlsof readxl package is used to import the Excel worksheetmutate_each_()of dplyr package is used to convert all character data type into factormutateof dplyr package is used to convert data values of Year field into integer
Unfortunately, mutate_each_() was deprecated in dplyr 0.7.0 and funs() was deprecated in dplyr 0.8.0.
- In view of this, we will re-write the code by using
mutate_at()(link is different from notes) as shown in the code chunk below - Instead of using
mutate_at(),across()can be used to derive the same outputs
col <- c("Country", "Continent")
globalPop <- read_xls("data/GlobalPopulation.xls",
sheet = "Data") %>%
mutate_at(col, as.factor) %>% # mutate_at()
mutate(Year = as.integer(Year))col <- c("Country", "Continent")
globalPop <- read_xls("data/GlobalPopulation.xls",
sheet = "Data") %>%
mutate(across(col, as.factor)) %>% # mutate(across())
mutate(Year = as.integer(Year))Both methods achieve the same results!
3-2: 3 Animated Data Visualisation: gganimate Methods
gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation. It does this by providing a range of new grammar classes that can be added to the plot object in order to customise how it should change with time.
transition_*(): Defines how the data should be spread out and how it relates to itself across timeview_*(): Defines how the positional scales should change along the animationshadow_*(): Defines how data from other points in time should be presented in the given point in timeenter_*()/exit_*(): Defines how new data should appear and how old data should disappear during the course of animationease_aes(): Defines how different aesthetics should be eased during transitions
3-2: 3.1 Building a Static Population Bubble Plot
In the code chunk below, the basic ggplot2 functions are used to create a static bubble plot.

ggplot(globalPop, aes(x = Old, y = Young,
size = Population,
colour = Country)) +
geom_point(alpha = 0.7,
show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2,12)) +
labs(title = 'Year: {frame_time}',
x = '% Aged',
y = '% Young') 3-2: 3.2 Building the Animated Bubble Plot
In the code chunk below,
transition_time()of gganimate is used to create transition through distinct states in time (i.e. Year)ease_aes()is used to control easing of aesthetics. The default islinear.- Other methods are: quadratic, cubic, quartic, quintic, sine, circular, exponential, elastic, back, and bounce.

ggplot(globalPop, aes(x = Old, y = Young,
size = Population,
colour = Country)) +
geom_point(alpha = 0.7,
show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(title = 'Year: {frame_time}',
x = '% Aged',
y = '% Young') +
transition_time(Year) +
ease_aes('linear') 3-2: 4 Animated Data Visualisation: plotly
In Plotly R package, both ggplotly() and plot_ly() support key frame animations through the frame argument/aesthetic. They also support an ids argument/aesthetic to ensure smooth transitions between objects with the same ID (which helps facilitate object constancy).
3-2: 4.1 Building an Animated Bubble Plot: ggplotly() Method
In this sub-section, an animated bubble plot will be created by using the ggplotly() method.
gg <- ggplot(globalPop,
aes(x = Old,
y = Young,
size = Population,
colour = Country)) +
geom_point(aes(size = Population,
frame = Year),
alpha = 0.7,
show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(x = '% Aged',
y = '% Young')
ggplotly(gg)
The animated bubble plot above includes a play/pause button and a slider component for controlling the animation
- Appropriate ggplot2 functions are used to create a static bubble plot. The output is then saved as an R object called gg.
ggplotly()is then used to convert the R graphic object into an animated svg object.
Notice that although show.legend = FALSE argument was used, the legend still appears on the plot. To overcome this problem, theme(legend.position='none') should be used as shown in the plot and code chunk below.
gg <- ggplot(globalPop,
aes(x = Old,
y = Young,
size = Population,
colour = Country)) +
geom_point(aes(size = Population,
frame = Year),
alpha = 0.7) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(x = '% Aged',
y = '% Young') +
theme(legend.position='none')
ggplotly(gg)3-2: 4.2 Building an Animated Bubble Plot: plot_ly() Method
In this sub-section, an animated bubble plot will be created with the plot_ly() method.
bp <- globalPop %>%
plot_ly(x = ~Old,
y = ~ Young,
size = ~Population,
color = ~Continent,
sizes = c(2,100),
frame = ~Year,
text = ~Country,
hoverinfo = "text",
type = 'scatter',
mode = 'markers'
) %>%
layout(showlegend = FALSE)
bpgg <- ggplot(globalPop,
aes(x = Old,
y = Young,
size = Population,
colour = Country)) +
geom_point(aes(size = Population,
frame = Year),
alpha = 0.7) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(x = '% Aged',
y = '% Young') +
theme(legend.position='none')
ggplotly(gg)The plot_ly() method is much simpler and easier to read and code compared to the ggplotly() method due to its simpler syntax and fewer layers of customisation.
- The execution time needed for plot_ly() is also lower.
3-2: 4.3 Improving Animated Bubble Plot: plot_ly() Method
Changes implemented: - Bubble size - Added legend
bp <- globalPop %>%
plot_ly(x = ~Old,
y = ~ Young,
size = ~Population,
color = ~Continent,
sizes = c(10,600),
frame = ~Year,
text = ~Country,
hoverinfo = "text",
type = 'scatter',
mode = 'markers'
)
bp- Getting Started
- Visit this link for a very interesting implementation of gganimate by an SMU senior
- Building an animation step-by-step with gganimate
- Creating a composite gif with multiple gganimate panels